package top.kaoshanji.p1ch02a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p1ch02a-38页a：向具体某人说"Hello"的Servlet
 * URL访问地址：/hello
 * @author kaoshanji
 * ^_^
 * create time 2025/4/2 17:14
 */
public class Hello extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_HTML.toString());
        PrintWriter out = resp.getWriter();

        String name = req.getParameter("name");
        System.out.println("获得表单name属性的值：" + name + " 转码前..");

        // 处理GET方法的解决乱码方式一：
        // String userName = new String(name.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        // System.out.println("获得表单name属性的值：" + userName + " 转码后..");

        out.println("<HTML>");
        out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>");
        out.println("<BODY>");
        out.println("Hello, " + name);
        out.println("</BODY></HTML>");

    }
}
